#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/3/19 00:33
# @Author  : huidong.bai
# @File    : NluEventParser.py
# @Software: PyCharm
# @Mail    : MasterBai2018@outlook.com
import pdb
import os
import json
from src.utils.common import trans_digit
import copy


class NluEventParser:
    nlu_events = {}

    def __init__(self, callback_path, input_path):
        self.__callback_folder_path = callback_path
        self.__input_folder_path = input_path
        self.__parse_events()

    def __process_callback_event(self):
        callback_contents = {}
        if not os.path.exists(self.__callback_folder_path):
            raise FileNotFoundError(f"Callback event folder '{self.__callback_folder_path}' does not exist.")

        for root, dirs, files in os.walk(self.__callback_folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                parent_folder = os.path.basename(os.path.dirname(file_path))
                try:
                    with open(file_path, 'r') as f:
                        callback_contents[parent_folder + '.' + file.replace(".json", "")] = json.load(f)
                except Exception as e:
                    print(f"Error processing callback event file '{file_path}': {e}")
        return callback_contents

    def __process_input_event(self):
        input_contents = {}
        if not os.path.exists(self.__input_folder_path):
            raise FileNotFoundError(f"Input event folder '{self.__input_folder_path}' does not exist.")

        for root, dirs, files in os.walk(self.__input_folder_path):
            for file in files:
                file_path = os.path.join(root, file)
                try:
                    with open(file_path, 'r') as f:
                        input_contents[file.replace(".json", "")] = json.load(f)
                except Exception as e:
                    print(f"Error processing input event file '{file_path}': {e}")
        return input_contents

    def __parse_events(self):
        try:
            callback_contents = self.__process_callback_event()
            input_contents = self.__process_input_event()
            self.nlu_events = {**callback_contents, **input_contents}
        except Exception as e:
            print(f"Error parsing events: {e}")

    def select(self, jsons: list, params: dict, default_callback):
        select_list = []
        searches = []
        for name in jsons:
            child = {}
            if default_callback and name:
                name = name.replace("default", default_callback)
            for key, value in params.items():
                if default_callback and key:
                    key = key.replace("default", default_callback)
                if name in key:
                    child[key] = value
            searches.append((name, child))

        for item in searches:
            search_result = self.__update(*item)
            select_list.append(search_result)

        return select_list

    def __update(self, name, child_list):
        if name not in self.nlu_events:
            print(f"Error: JSON '{name}' not found.")
            return None

        json_data = self.nlu_events[name]
        if not child_list:
            return json_data

        update_json = copy.deepcopy(json_data)
        for key, value in child_list.items():
            if key.startswith(name+"."):
                keys = key[len(name+"."):].split('.')
            current_dict = update_json
            for k in keys[:-1]:
                if k not in current_dict:
                    print(f"Error: Key '{k}' not found in JSON '{update_json}'.")
                    return None
                current_dict = current_dict[k]

            last_key = keys[-1]
            if last_key not in current_dict:
                print(f"Error: Key '{last_key}' not found in JSON '{update_json}'.")
                return None

            if not value:
                print(f"Error: key:{last_key}, value:'{value}'.")
                return None
            elif trans_digit(value) is not None:
                new_value = trans_digit(value)
            elif value.lower() == "true":
                new_value = True
            elif value.lower() == "false":
                new_value = False
            elif os.path.exists(value):
                with open(value, 'r') as f:
                    new_value = json.load(f)
            else:
                new_value = value

            current_dict[last_key] = new_value

        return update_json


if __name__ == '__main__':
    # 初始化 NluEventParser 并加载文件夹路径
    callback_folder_path = "./events/CallBackEvent"
    input_folder_path = "./events/InputEvent"

    try:
        event_parser = NluEventParser(callback_folder_path, input_folder_path)
        # print(event_parser.nlu_events)

        # 测试 update 方法
        json_names = ["AppDIRCallback.close", "AppDIRCallback.open"]
        children = {
            "AppDIRCallback.close.data.statusCode": "222222",
            "AppDIRCallback.open.data.statusCode": "-2222",
            "AppDIRCallback.close.data.data.packageName": "com.test.cnsssss",
            "AppDIRCallback.close.data.data.appName": "./events/Public/NoneDict.json"
        }
        new_json = event_parser.select(json_names, children)
        print("Updated JSON:", new_json)
    except Exception as e:
        print(f"Error initializing NluEventParser: {e}")
